import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:mirror/AppStyle.dart';
import 'package:mirror/CommonLoading.dart';
import 'package:mirror/Util.dart';
import 'package:mirror/api/UserApi.dart';
import 'package:mirror/bean/UserBean.dart';
import 'package:mirror/service/NetworkService.dart';
import 'package:mirror/service/ProviderService.dart';
import 'package:mirror/widget/AvatarWidget.dart';
import 'package:provider/provider.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({super.key});

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  UserBean? user;
  String changedLocalPath = "";
  String? avatar;

  @override
  void initState() {
    super.initState();
    refresh();
  }

  @override
  Widget build(BuildContext context) {
    var myData = Provider.of<ProviderData>(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text("设置"),
        actions: [
          InkWell(
              onTap: () {},
              child: const Padding(
                padding: EdgeInsets.symmetric(horizontal: 20),
                child: Center(child: Text("保存")),
              ))
        ],
      ),
      body: SafeArea(
        child: user == null
            ? Center(
                child: LoadingAnimationWidget.discreteCircle(
                  color: Colors.blue,
                  size: 50,
                ),
              )
            : Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      InkWell(
                        onTap: () async {
                          XFile? res = await ImagePicker()
                              .pickImage(source: ImageSource.gallery);
                          if (res != null) {
                            var data = await res.readAsBytes();
                            var selectedAvatarData = await Util.crop(data);
                            if (selectedAvatarData != null) {
                              var filePath =
                                  "${await Util.getTmpPath()}tmpAvatar.png";
                              await Util.saveFile(
                                  path: filePath, data: selectedAvatarData);
                              setState(() {
                                changedLocalPath = filePath;
                              });

                              avatar = await UserApi.changeAvatar(
                                  path: changedLocalPath);

                              await UserApi.updateProfile(avatar: avatar);
                              await UserApi.updateLocal(avatar: avatar);
                              user = await UserApi.getUser();
                              setState(() {
                                myData.updateUserAvatar(avatar.toString());
                              });
                            }
                          }
                        },
                        child: Container(
                          margin: const EdgeInsets.symmetric(vertical: 5),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 10),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: Constant.boxShadow,
                            borderRadius: Constant.borderRadius,
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text("修改头像："),
                              AvatarWidget(
                                imageUrl: myData.userAvatar.isEmpty
                                    ? "${user?.userAvatar}"
                                    : myData.userAvatar,
                                size: 50,
                                circular: 30,
                              ),
                            ],
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () async {
                          String? res = await Util.showBottomInputDialog(
                              title: "请输入昵称", hint: '请输入昵称');
                          if (res != null && res.isNotEmpty) {
                            try {
                              CommonLoading.show();
                              await UserApi.updateProfile(nickName: res);
                              await UserApi.updateLocal(nickName: res);
                              CommonLoading.hide();
                              refresh();
                            } catch (e) {
                              CommonLoading.hide();
                              if (e is RequestError) {
                                Util.toast(e.message);
                              } else {
                                print(e);
                              }
                            }
                          }
                        },
                        child: Container(
                          margin: const EdgeInsets.symmetric(vertical: 5),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 10),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              boxShadow: Constant.boxShadow,
                              borderRadius: Constant.borderRadius),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text("修改昵称："),
                              Expanded(
                                  child: Align(
                                      alignment: Alignment.centerRight,
                                      child: Text("${user?.nickName}")))
                            ],
                          ),
                        ),
                      ),
                      Container(
                        margin: const EdgeInsets.symmetric(vertical: 5),
                        padding: const EdgeInsets.symmetric(
                            horizontal: 10, vertical: 10),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: Constant.boxShadow,
                            borderRadius: Constant.borderRadius),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: const [
                            Text("用户邮箱："),
                            Expanded(
                                child: TextField(
                              textAlign: TextAlign.end,
                              decoration:
                                  InputDecoration.collapsed(hintText: "请输入邮箱"),
                            ))
                          ],
                        ),
                      ),
                      InkWell(
                        onTap: () async {
                          DateTime? date = await showDatePicker(
                              context: context,
                              initialDate: DateTime(2000),
                              firstDate: DateTime(1960),
                              lastDate: DateTime.now());
                          if (date != null) {
                            print(date.year);
                            try {
                              CommonLoading.show();
                              var birthday =
                                  "${date.year}-${'${date.month}'.padLeft(2, "0")}-${'${date.day}'.padLeft(2, "0")}";
                              await UserApi.updateProfile(
                                  userBirthday: birthday);
                              await UserApi.updateLocal(userBirthday: birthday);
                              CommonLoading.hide();
                              refresh();
                            } catch (e) {
                              CommonLoading.hide();
                              if (e is RequestError) {
                                Util.toast(e.message);
                              } else {
                                print(e);
                              }
                            }
                          }
                        },
                        child: Container(
                          margin: const EdgeInsets.symmetric(vertical: 5),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 10),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              boxShadow: Constant.boxShadow,
                              borderRadius: Constant.borderRadius),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text("生日："),
                              Text("${user?.userBirthday}" == "null"
                                  ? "请设置生日"
                                  : "${user?.userBirthday}")
                            ],
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () async {
                          List? res = await Util.showBottomLabelDialog(
                              lists: json.decode("${user?.userHobby}"));
                          if (res != null) {
                            String hobby = json.encode(res);
                            try {
                              CommonLoading.show();
                              await UserApi.updateProfile(userHobby: hobby);
                              await UserApi.updateLocal(userHobby: hobby);
                              CommonLoading.hide();
                              refresh();
                            } catch (e) {
                              CommonLoading.hide();
                              if (e is RequestError) {
                                Util.toast(e.message);
                              } else {
                                print(e);
                              }
                            }
                          }
                        },
                        child: Container(
                          margin: const EdgeInsets.symmetric(vertical: 5),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 10),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              boxShadow: Constant.boxShadow,
                              borderRadius: Constant.borderRadius),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text("爱好："),
                              Expanded(child: getHobbyLayout())
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }

  Future<void> refresh() async {
    user = await UserApi.getUser();
    avatar = user?.userAvatar;
    print(avatar);
    setState(() {});
  }

  getHobbyLayout() {
    if ('${user?.userHobby}'.isEmpty || '${user?.userHobby}' == 'null') {
      return const Text("请设置爱好");
    } else {
      List list = json.decode("${user?.userHobby}");
      return Wrap(
        spacing: 10,
        children: List.generate(
            list.length,
            (index) => Padding(
                  padding: const EdgeInsets.symmetric(vertical: 5),
                  child: Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    decoration: BoxDecoration(
                        color: Constant.mainColor,
                        borderRadius: Constant.borderRadius),
                    child: Text(
                      list[index],
                      style: const TextStyle(color: Colors.white, fontSize: 10),
                    ),
                  ),
                )),
      );
    }
  }
}
